import ctypes
import json
from typing import List
from dataclasses import dataclass

@dataclass
class HistData:
    date: str
    open: float
    high: float
    low: float
    close: float
    volume: float

class PyDataLoader:
    """Python数据加载器实现"""
    def __init__(self):
        from .fetch import DataFetcher
        self.fetcher = DataFetcher()
        
    def load_history(self, code: str, market: str, days: int) -> List[HistData]:
        """加载历史数据"""
        df = self.fetcher.fetch_history(code, market, days)
        if df.empty:
            return []
            
        return [
            HistData(
                date=row['date'],
                open=row['open'],
                high=row['high'],
                low=row['low'],
                close=row['close'],
                volume=row['volume']
            ) for _, row in df.iterrows()
        ]

# C接口导出
lib = ctypes.CDLL(None)
loader = PyDataLoader()

@ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int)
def c_load_history(code, market, days):
    """供C++调用的数据加载接口"""
    try:
        code_str = code.decode('utf-8')
        market_str = market.decode('utf-8')
        data = loader.load_history(code_str, market_str, days)
        return json.dumps([d.__dict__ for d in data]).encode('utf-8')
    except Exception as e:
        print(f"加载历史数据出错: {e}")
        return json.dumps([]).encode('utf-8')
        
# 注册C接口
lib.set_py_data_loader(c_load_history)